<?php
class QAs extends CActiveRecord {
	/** Q&A Status */
	const STATUS_SOLVED = 2;
	const STATUS_UNSOLVED = 1;
	const STATUS_REPLY = 3;
	/** If Q&A is a topic, the parent field would be zero */
	const PARENT_TOPIC = 0;
	
	public $replied;
	// Replies' count, only for topic
	public $repliesCount;
	public $lastReply;
	
	const COOKIE_KEY = 'qAHistory';
	const COOKIE_EXPIRE = 2592000;
	const HISTORY_MAX = 7;
	
	public $verifyCode;
	
	public static function model($className = __CLASS__) {
		return parent::model($className);
	}

	public function tableName() {
		return strtolower('QAs');
	}
	
	public function rules() {
		return array(
			array('qaStatus, qaAuthor', 'required'),
			array('qaTitle', 'required', 'message' => '标题不能为空。', 'on' => array('postNewTopic')),
			array('qaContent', 'required', 'message' => '内容不能为空。'),
			array('qaTitle', 'length', 'max' => 255),
			array('verifyCode', 'captcha', 'on' => array('postNewTopic'), 'message' => '验证码输入错误。')
		);
	}
	
	public function safeAtrributes() {
		return array('qaTitle', 'qaContent');
	}
	
	public function relations() {
		return array(
			'author' => array(self::BELONGS_TO, 'ForumMembers', 'qaAuthor',
				'joinType' => 'INNER JOIN'
			)
		);
	}
	
	public function scopes() {
		return array(
			'solved' => array(
				'condition' => 'qaStatus = '.self::STATUS_SOLVED
			),
			'unsolved' => array(
				'condition' => 'qaStatus = '.self::STATUS_UNSOLVED
			),
			'all' => array(
				'condition' => '1'
			),
			'topic' => array(
				'condition' => 'qaParent = 0'
			),
			'desc' => array(
				'order' => 'qaId DESC'
			)
		);
	}
	
	public function getStatusOptions() {
		return array(
			self::STATUS_SOLVED => '已解决',
			self::STATUS_UNSOLVED => '未解决'
		);
	}
	
	public function getReplies() {
		if($this->qaParent == self::PARENT_TOPIC) {
			$criteria = new CDbCriteria;
			$criteria->condition = 'qaParent = '.$this->qaId;
			$criteria->order = 'qaDate ASC';
			return QAs::model()->findAll($criteria);
		}
		return null;
	}
	
	public function isResolved() {
		if($this->qaParent == self::PARENT_TOPIC) {
			return $this->qaStatus == self::STATUS_SOLVED; 
		}
	}
	
	public function getStatusText() {
		$options = $this->getStatusOptions();
		return isset($options[$this->qaStatus]) ? $options[$this->qaStatus] : "未知{$this->qaStatus}";
	}
	
	// After finds a topic, gets the topic's number of replies
	public function onAfterFind() {
		$this->getCountReplies();
	}

	public function isTopic() {
		return $this->qaParent == self::PARENT_TOPIC;
	}
	
	public function getLastReply() {
		if($this->isTopic()) {
			$c = new CDbCriteria; 
			$c->order = 'qaDate DESC'; 
			$c->condition = 'qaParent = '.$this->qaId;
			return QAs::model()->find($c);
		}
		return null;
	}
	
	public function getCountReplies() {
		if($this->qaParent !== self::PARENT_TOPIC) {
			$criteria = new CDbCriteria;
			$criteria->condition = 'qaParent = '.$this->qaId;
			$this->repliesCount = $this->count($criteria);
		}
	}
	
	public static function addToHistory($id) {
		$ids = self::getIdsFromHistory();
		self::clearHistory();
		if(count($ids) >= self::HISTORY_MAX) {
			$ids = array_slice($ids, count($ids)-self::HISTORY_MAX, self::HISTORY_MAX);
		}
		if( ! array_key_exists($id, array_flip($ids))) {
			$ids[] = $id;
			return setcookie(self::COOKIE_KEY, serialize($ids), time()+self::COOKIE_EXPIRE, '/');
		}
		return false;
	}
	
	public static function getIdsFromHistory() {
		return isset($_COOKIE[self::COOKIE_KEY]) ? unserialize($_COOKIE[self::COOKIE_KEY]) : array();
	}
	
	public static function clearHistory() {
		return setcookie(self::COOKIE_KEY, serialize(array()), time()-3600);
	}
	
	public function canReply() {
		$userId = ForumMembers::isLogin();
		if($userId) {
			$user = ForumMembers::model()->findByPk($userId);
			return $user->uid == $this->qaAuthor || $user->getIsAdmin();
		}
		return false;
	}
	
	public function getNotifyingMailText($qa) {
		if(($c = Yii::app()->getController()) !== null) {
			$qaViewUrl = $c->createAbsoluteUrl('/qas/view', array('id' => $qa->qaId));
			$baseUrl = BASE_URL;
			return '
您好，'.$qa->author->userName().'，<br />
<br />
您在在线问吧的提问“'.htmlspecialchars($qa->qaTitle).'”，咨询师'.$this->author->userName().'已经对您进行了回复！<br />
<br />
请把以下地址复制到浏览器地址栏查看：<br />
'.$qaViewUrl.'<br />
<br />
任何疑问欢迎联系我们: <br />
网址: '.$baseUrl.'<br />
咨询热线: 020-62728787，83644639<br />
邮件: huiyn2009@163.com<br />
<br />
广州心理咨询网';
		}
		return '';
	}
}
